package com.leetcode.LeetCode精选TOP面试题;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 覃国强
 * @date 2022-05-27 17:45
 */
public class 题库_0073_矩阵置零 {

  static
  class Solution {
    public void setZeroes(int[][] matrix) {
      if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
        return;
      }
      Set<Integer> zeroRows = new HashSet<>();
      Set<Integer> zeroColumns = new HashSet<>();

      for (int i = 0; i < matrix.length; ++i) {
        for (int j = 0; j < matrix[0].length; ++j) {
          if (matrix[i][j] == 0) {
            zeroRows.add(i);
            zeroColumns.add(j);
          }
        }
      }

      for (int i : zeroRows) {
        for (int j = 0; j < matrix[0].length; ++j) {
          matrix[i][j] = 0;
        }
      }

      for (int j : zeroColumns) {
        for (int i = 0; i < matrix.length; ++i) {
          matrix[i][j] = 0;
        }
      }
    }

    public void setZeroes0(int[][] matrix) {
      if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
        return;
      }
      boolean rowHasZero = matrix[0][0] == 0;
      boolean columnHasZero = matrix[0][0] == 0;
      for (int i = 1; i < matrix.length && !columnHasZero; ++i) {
        columnHasZero = matrix[i][0] == 0;
      }
      for (int j = 1; j < matrix[0].length && !rowHasZero; ++j) {
        rowHasZero = matrix[0][j] == 0;
      }

      for (int i = 0; i < matrix.length; ++i) {
        for (int j = 0; j < matrix[0].length; ++j) {
          if (matrix[i][j] == 0) {
            matrix[i][0] = 0;
            matrix[0][j] = 0;
          }
        }
      }

      for (int i = 0; i < matrix.length; ++i) {
        if (matrix[i][0] == 0) {
          for (int j = 0; j < matrix[0].length; ++j) {
            matrix[i][j] = 0;
          }
        }
      }

      for (int j = 0; j < matrix[0].length; ++j) {
        if (matrix[0][j] == 0) {
          for (int i = 0; i < matrix.length; ++i) {
            matrix[i][j] = 0;
          }
        }
      }

      if (rowHasZero) {
        for (int j = 0; j < matrix[0].length; ++j) {
          matrix[0][j] = 0;
        }
      }

      if (columnHasZero) {
        for (int i = 0; i < matrix.length; ++i) {
          matrix[i][0] = 0;
        }
      }
    }
  }

}
